package com.chess.chessplay.controller;

import com.chess.chessplay.pojo.Player;
import com.chess.chessplay.pojo.R;
import com.chess.chessplay.service.PlayerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/player")
public class PlayController {

    @Autowired
    private PlayerService playerService;

    @ResponseBody
    @RequestMapping(value = "/playerLogin/{username}/{password}",method = RequestMethod.POST)
    public R playLogin(@PathVariable("username") String username, @PathVariable("password") String password, HttpSession session) {
        Player playerByUsername = playerService.findPlayerByUsername(username);
        if ( playerByUsername == null ) { //账号不存在
            return R.error().Data("msg","账号不存在");
        }
        else if ( !password.equals(playerByUsername.getPassword()) ) {  //账号密码不匹配
            return R.error().Data("msg","账号密码不匹配");
        }
        else {  //登陆成功
            session.setAttribute("player",playerByUsername);
            System.out.println(playerByUsername.toString());
            return R.ok().Data("play",playerByUsername);
        }
    }

    @ResponseBody
    @PostMapping("/register")
    public R PlayerRegister(@RequestBody Player player, HttpSession session){
        String username = player.getUsername();

        Player playerByUsername = playerService.findPlayerByUsername(username);
        if ( playerByUsername != null ) { //注册失败
            return R.error().Data("msg","账号已存在");
        }
        else { //成功
            playerService.InsertPlayer(player);
            playerByUsername = playerService.findPlayerByUsername(username);
            session.setAttribute("player",playerByUsername);
            return R.ok();
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/index.html";
    }

    @RequestMapping("/MyInfo")
    public String ToMyInfo(){
        return "player/myselfInfo";
    }

    @PostMapping("/update")
    public String update(Player player, HttpSession session) {
        System.out.println(player);
        Player player1 = (Player) session.getAttribute("player");

        player.setUserid(player1.getUserid());
        playerService.updatePlayerById(player);

        session.setAttribute("player",player);
        return "redirect:/main";
    }

    @RequestMapping("/alone")
    public String AloneGame() {
        return "player/aloneChess";
    }
}
